package com.wits.platform.common.persistence;
import java.sql.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springside.modules.persistence.SearchFilter;

import com.google.common.collect.Maps;
import com.wits.platform.common.utils.DateUtil;

public class HibernatePropertyFilter extends SearchFilter{
	

	private static final String DATE_PARDEN_SHORT="\\d{4}-\\d{1,2}-\\d{1,2}";
	
	public HibernatePropertyFilter(String fieldName, Operator operator,Object value) {
		super(fieldName, operator, value);
	}

	public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			if (StringUtils.isBlank((String) value)) {
				continue;
			}
			
			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length < 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String filedName = names[1];
			Operator operator = Operator.valueOf(names[0]);
			
			if(names.length>2){
				//key=names[0]+"_"+names[1];
				//日期类型处理
				String type=names[2];
				if(HibernatePropertyType.Date.getValue().equals(type)){
					String v=String.valueOf(value);
					if(v.matches(DATE_PARDEN_SHORT)){
						value=DateUtil.parse(v, DateUtil.PATTERN_SIMPLE);
					}else{
						value=DateUtil.parse(v, DateUtil.PATTERN_FULL);
					}
					
					//value=Date.valueOf(String.valueOf(value));
				}
			}

			// 创建searchFilter
			HibernatePropertyFilter filter = new HibernatePropertyFilter(filedName, operator, value);
			filters.put(key, filter);
		}
		
		return filters;
	}
}